package com.ikingtech.platform.service.system.organization.service;

import com.ikingtech.framework.sdk.organization.api.OrgUserApi;
import com.ikingtech.framework.sdk.organization.model.OrganizationDTO;
import com.ikingtech.framework.sdk.organization.model.OrganizationManagerDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.organization.entity.OrganizationDO;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class ModelConverter {

    private final OrgUserApi orgUserApi;

    public List<OrganizationDTO> modelConvert(List<OrganizationDO> entities) {
        List<OrganizationManagerDTO> managers = this.orgUserApi.loadManagers(Tools.Coll.convertList(entities, OrganizationDO::getManagerId));
        Map<String, OrganizationManagerDTO> managerMap = Tools.Coll.convertMap(managers, OrganizationManagerDTO::getUserId, manager -> manager);
        return Tools.Coll.convertList(entities, entity -> this.modelConvert(entity, managerMap.get(entity.getManagerId())));
    }

    public OrganizationDTO modelConvert(OrganizationDO entity) {
        return this.modelConvert(entity, this.orgUserApi.loadManager(entity.getManagerId()));
    }

    public OrganizationDTO modelConvert(OrganizationDO entity,
                                        OrganizationManagerDTO manager) {
        OrganizationDTO org = Tools.Bean.copy(entity, OrganizationDTO.class);
        if (null != org.getStatus()) {
            org.setStatusName(org.getStatus().description);
        }
        org.setManager(manager);
        return org;
    }
}
